package com.sep.web;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpSession;

import my.mvc.RequestContext;

public class UserAction {
	
	public void login(RequestContext rc) throws Exception {
		rc.request().setCharacterEncoding("UTF-8");
		// 是否允许账户登录
		boolean isTrueAccount = false;

		String userName = rc.request().getParameter("username");
		String userPwd = rc.request().getParameter("userpwd");

		// 数据库验证账户
		if (userName.equals("qq@qq.com") && userPwd.equals("qq")) {
			isTrueAccount = true;
		}
		
		// 获得HttpSession对象
		HttpSession session = rc.session();
		if (isTrueAccount) {
			// 在session中放入username代表已经登陆
			session.setAttribute("username", userName);
			session.setAttribute("nickname", userName);
			// 使用客户端跳转（重定向）
			rc.redirect("/account.jsp");
		} else {
			session.setAttribute("login_error", "用户名或密码错误");
			rc.redirect("/login.jsp");
		}
	}
	
	public void logout(RequestContext rc) throws Exception {
		// 获得HttpSession对象
		HttpSession session = rc.session();
		if (session.getAttribute("username") != null) {
			// 在session中移除username
			session.removeAttribute("username");
			session.removeAttribute("nickname");
		}
		// 使用客户端跳转（重定向）
		rc.redirect("/login.jsp");
//		req.getRequestDispatcher("/login.jsp").forward(req, resp);
	}
	
	public void register(RequestContext rc) throws IOException{
		
		rc.request().setCharacterEncoding("UTF-8");
		
		String username = rc.request().getParameter("username");
		String userpwd1 = rc.request().getParameter("userpwd1");
		String userpwd2 = rc.request().getParameter("userpwd2");
		
		boolean legal = false;
		HttpSession hs = rc.session();
		
		//空表单刷新
		if(username == null || userpwd1 == null || userpwd2 == null){
			rc.redirect("/register.jsp");
			return;
		}
		// 验证
		if(!username.equals("") && !userpwd1.equals("") && userpwd1.equals(userpwd2)){
			legal = true;
		}else if(!userpwd1.equals(userpwd2)){
			hs.setAttribute("error_type", "输入的密码不一致");
			rc.redirect("/register.jsp");
		}else{
			hs.setAttribute("error_type", "信息不完整");
			rc.redirect("/register.jsp");
		}
		
		if(legal){
			hs.setAttribute("username", username);
			hs.setAttribute("nickname", username);
			rc.redirect("/account.jsp");
		}
	}
	
	public void editInfo(RequestContext rc) throws IOException{
		rc.request().setCharacterEncoding("UTF-8");
		String id = rc.request().getParameter("edit-id");
		String value = rc.request().getParameter("edit-value");
		
		//数据库操作
		HttpSession session = rc.session();
		session.setAttribute(id, value);
		
		rc.redirect("/account.jsp");
	}
}
